<template>
  <div>
    <input type="text" v-model="state2.name" />
    <input type="text" v-model="state2.age" />
    <button @click="addItem">添加数据</button>
    <ul>
      <li v-for="(item, index) in state2.list" :key="index">
        {{ item.name }}--{{ item.age }}
      </li>
    </ul>
  </div>
</template>
<script>
import { ref, reactive, watch } from "vue";
/**
ref和reactive的区别 当使用ref ref(8)创建简单数据类型的话
在template使用的时候vue会自动添加.value
如果通过reactive({value:8})这种来创建的话template不会自动加上value.

 */
export default {
  setup() {
    // 渲染列表
    // const { state, removeItem } = renderList();
    const { state2, addItem } = newState();
    return {
      addItem,
      state2,
    };
  },
};
// 渲染列表的逻辑
// function renderList() {
//   const state = reactive({
//     list: [
//       {
//         name: "GuanYu",
//         age: "56",
//       },
//       {
//         name: "ZhangFei",
//         age: "54",
//       },
//       {
//         name: "MaChao",
//         age: "77",
//       },
//     ],
//   });
//   function removeItem(i) {
//     state.list = state.list.filter((val, index) => i !== index);
//   }
//   return { state, removeItem };
// }
// 添加的逻辑
function newState(state) {
  const state2 = reactive({
    name: "",
    age: "",
    list: [
      {
        name: "GuanYu",
        age: "56",
      },
      {
        name: "ZhangFei",
        age: "54",
      },
      {
        name: "MaChao",
        age: "77",
      },
    ],
  });
  function addItem() {
    state2.list.push({ name: state2.name, age: state2.age });
    state2.name = "";
    state2.age = "";
  }
  return {
    state2,
    addItem,
  };
}
</script>
<style scoped></style>
